package com.mybatisPlus.springSecurity;

import com.mybatisPlus.Utils.BeanUtils;
import com.mybatisPlus.Utils.JwtUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 利用过滤器进行token校验
 * Author: lihewei
 * createAt: 2022/4/15
 */
//注释掉component 防止该过滤器成为springboot的全局过滤器
//@Component
public class JwtFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        //效验token
        if (token != null && JwtUtils.verify(token)) {
            String username=JwtUtils.getString(token,"username");
            //获取bean
            UserDetailsImpl userDetail = (UserDetailsImpl) BeanUtils.getBean("userDetail");
            UserDetails userDetails = userDetail.loadUserByUsername(username);
            //将登陆信息传入SpringSecurity
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }else {
            //token无效,拒绝登录
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write("{\"code\":402,\"msg\":\"拒绝访问,请先登录" + "\"}");
            writer.close();
            return;
        }
        filterChain.doFilter(request,response);
    }
}
